// router.js
import {
	RouterMount,
	createRouter
} from 'uni-simple-router';
import commonApi from "@/services/api/common.js";
import $store from '@/store/index.js';

let iframeGo = false //是否加载了统计页面获取统计
let isNest = false //是否执行了
let isConfig = false // 是否加载了config
let isConfigComplete = false // 是否加载完毕config


const router = createRouter({
	encodeURI: false,
	platform: process.env.VUE_APP_PLATFORM,
	APP:{
		registerLoadingPage: false,
		animation:{
			animationType:'fade-in'
		}
	},
	routes: [...ROUTES]
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
	console.log(to);
	console.log(from);
	next();
	// if(to.name == "chatMsg"){
	// 	if(to.NAVTYPE != 'back'){
	// 		next();
	// 	}
	// }else{
	// 	next();
	// }
});
// 全局路由后置守卫
router.afterEach((to, from) => {
	if(to.path == "/pages/start/index"){
		uni.getNetworkType({
			success: (e) => {
				if(e.networkType != 'none'){
					init()
				}else{
					uni.showLoading({
						title:getApp().$t("loadding.title.waitNetwork")
					})
					uni.onNetworkStatusChange((res)=>{
						if(res.isConnected){
							uni.hideLoading()
							init()
						}
					})
				}
			}
		})
		
	}
	console.log('跳转结束')
})

async function init() {
	uni.$on('iframeGo',(e)=>{
		iframeGo = true
		if(!isNest && isConfigComplete){
			isNest = true
			nestGo()
		}
	})
	//如果没有加载config
	if(isConfig == false){
		try{
			//加载过一次
			isConfig = true
			//获取config配置
			await uni.$config.getConfigRequest()
			//加载完毕记录
			isConfigComplete = true 
			if(!uni.$config.plat_status){
				uni.showModal({
					title:'提示',
					content:'平台已关闭',
					showCancel:false,
					success:(e)=>{
						plus.runtime.quit();
					}
				})
				return
			}
		}catch(e){
			//加载完毕记录
			isConfigComplete = true
			uni.showToast({
				title: e
			});
			return
		}
	}
	//如果加载完了统计，直接进行下一步，并且监听中的就不再执行了
	if(iframeGo && isConfigComplete){
		isNest = true
		nestGo()
	}
}
async function nestGo(){
	//获取app更新
	await commonApi.appUpdate(0)
	try{
		console.log('88888888888888888888888');
		await $store.dispatch('initLogin')
		router.pushTab({
			name: 'index'
		});
	}catch(e){
		console.log('---------------------');
		if(uni.$config.is_reg){
			router.replaceAll({
				name: 'login'
			});
		}else{
			await $store.dispatch('autoLogin')
			router.pushTab({
				name: 'index'
			});
		}
	}
	uni.$off('iframeGo')
}

export {
	router,
	RouterMount
}
